package util

import (
	"sync"
)

var (
	mutex sync.Mutex
)

type SegmentRunner = func(int, int, SegmentDone)
type SegmentDone = func()
type SeqmentAllFinish = func()

func SegmentExec(runner SegmentRunner, finish SeqmentAllFinish, total, segSize int) {
	roundCount := CeilToInt(float64(total) / float64(segSize))
	roundRemain := total % segSize
	waitExecCount := roundCount
	for round := 0; round < roundCount; round++ {
		roundOffset := round * segSize
		roundLimit := segSize
		if (roundOffset + roundLimit) > total {
			roundLimit = roundRemain
		}
		go runner(round, roundLimit, func() {
			mutex.Lock()
			waitExecCount--
			mutex.Unlock()
			if waitExecCount == 0 {
				finish()
			}
		})
	}
}
